import PateoAuthButtons from '@/components/common/PateoAuthButtons';
import { MinusCircleOutlined, PlusCircleOutlined } from '@ant-design/icons';
import { Card, Button, DatePicker, Modal, Row, Col, Input, Form, message, Table } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import React, { useState, useMemo, useEffect } from 'react';


interface DataType {
  vin: string;
  expireTime: string;
}

const DMMessageManagement: React.FC<any> = props => {
  const {
    loading,
    dispatch,
    location: { pathname = '/' },
  } = props;

  const [params, setParams] = useState({
    pageNum: 1, //当前页
    pageSize: 10,  // 每页条数
  });
  const [pageCount, setPageCount] = useState(10);

  const [vehichleList, setVehichleList] = useState<DataType[]>();
  const handleFlash = ((paramsFlash: any) => {
    dispatch({
      type: 'dmMessage/getFetchPage',
      payload: { url: '/dm-process-service/config/vins', ...paramsFlash }
      ,
      callback: (res: any) => {
        const list = res?.data?.list;
        if (list.length === 0 && res.data.pageNum > 1) {
          handleFlash({
            pageNum: res.data.pageNum - 1,
            pageSize: res.data.pageSize
          });
        } else {
          setVehichleList(res?.data?.list);
          setParams({
            pageNum: res.data.pageNum,
            pageSize: res.data.pageSize
          });
          setPageCount(res.data.pageCount);
          setSelectedRowKeys([]);
        };
      }
    });
  });

  useEffect(() => {
    handleFlash(params);
  }, []);

  const columns = [
    {
      title: 'vin',
      width: 300,
      dataIndex: 'vin',
    },
    {
      title: '过期时间',
      dataIndex: 'expireTime',
    },
    {
      title: '操作',
      render: (text: any, record: any) => {
        const updateHandler = () => {
          setEditingData({
            ...record,
            expireTime: moment(record.expireTime),
          });
          setEditModalVisible(true);
          // form.setFieldsValue({});
          form.resetFields();
        };
        return (
          <Button type="link" onClick={updateHandler}>
            更新
          </Button>
        );
      },
    },
  ];

  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [editModalVisible, setEditModalVisible] = useState<boolean>(false);
  const [editingData, setEditingData] = useState<DataType>({ vin: '', expireTime: '' });
  const [defaultDate, setDefaultDate] = useState('');
  const [modalLoading, setModalLoading] = useState<boolean>(false);
  const enableBatchDeleteBtn = useMemo(() => selectedRowKeys.length > 0, [selectedRowKeys]);
  const closeModal = () => {
    setModalVisible(false);
    form.resetFields();
  };
  const closeEditModal = () => setEditModalVisible(false);
  const openCreationDialog = () => {
    setModalVisible(true);
    form.resetFields();
  };

  const [form] = Form.useForm();
  const handleCreate = () => {
    // 新增事件,
    form.validateFields().then((values) => {
      form.submit();
      onFinish(values);
      form.resetFields();
    }).catch((e: any) => { });

  };

  const handleUpdate = async () => {
    // 更新事件
    form.validateFields().then((values) => {
      const formValues = {
        ...values,
        expireTime: moment(values.expireTime).format('YYYY-MM-DD HH:mm:ss')
      };
      dispatch({
        type: 'dmMessage/putObj',
        payload: { url: '/dm-process-service/config/vins', ...formValues },
        callback: (res: any) => {
          if (res.statusCode === '0') {
            message.success('更新成功');
            handleFlash(params);
          }
        }
      });
      setEditModalVisible(false);
    }
    ).catch((e: any) => { });

  };

  const handleDelete = () => {
    // 删除事件
    const { dispatch } = props;
    const delVinList = selectedRowKeys;
    const delVinListParam = {
      data: delVinList
    };
    dispatch({
      type: 'dmMessage/delObj',
      payload: { url: '/dm-process-service/config/vins', ...delVinListParam },
      callback: async (response: any) => {
        if (response.statusCode === '0') {
          message.success('删除成功');
          // 在删除表单最后一页所有数据时,自动返回上一页
          const totalPages = Math.ceil((pageCount - selectedRowKeys.length) / params.pageSize);
          const currentPageNumTmp = params.pageNum > totalPages ? totalPages : params.pageNum;
          const currentPageNum = currentPageNumTmp < 1 ? 1 : currentPageNumTmp;
          const newParams = {
            ...params,
            pageNum: currentPageNum
          };
          handleFlash(newParams);
        };
      }
    });
  };


  const paginationProps = {
    showSizeChanger: true,
    showQuickJumper: true,
    total: pageCount,
    pageSize: params.pageSize,
    current: params.pageNum,
    showTotal: () => (
      <span>共&nbsp;{pageCount === undefined ? 0 : pageCount}&nbsp;条</span>
    ),
  };

  const tableProps = {
    rowSelection: {
      type: 'checkbox',
      selectedRowKeys,
      onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
        setSelectedRowKeys(selectedRowKeys);
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      },
    },
    columns, //列表标题信息
    dataSource: vehichleList, //要渲染的数据信息
    loading: loading, //设置加载的lodalind
    rowKey: (record: DataType) => {
      return record.vin;
    }, //接收每一行信息参数,设置每一行的key
    pagination: paginationProps,
  };

  const layout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
  };

  const onFinish = (values: any) => {
    // 批量添加事件
    // 1. 将数据格式化成{"data:[{"vin1":"YYYY-MM-DD HH:mm:ss"}，{"vin1":"YYYY-MM-DD HH:mm:ss"}]"}
    // 2. 发送请求添加
    // 3. get请求再次获取列表
    const { dispatch } = props;
    const { formValues } = values;
    const addVinList = formValues.map((item: any) => ({
      ...item,
      expireTime: moment(item?.expireTime).format('YYYY-MM-DD HH:mm:ss')
    }));
    const addVinListParam = {
      data: addVinList
    };
    setModalLoading(true);
    // 发送请求
    dispatch({
      type: 'dmMessage/postFetchPage',
      payload: {
        url: '/dm-process-service/config/vins', ...addVinListParam,
      },
      callback: (response: any) => {
        if (response.statusCode === '0') {
          message.success('添加成功');
          handleFlash(params);
          setModalVisible(false);
          setModalLoading(false);
        }
      }
    });
  };

  const btns = [
    {
      title: '批量添加',
      key: 'add',
      auth: 'dmMessageManagement_add',
      onConfirm: openCreationDialog,
    },
    {
      title: '批量删除',
      key: 'delete',
      auth: 'dmMessageManagement_delete',
      message: '确认删除吗？',
      Popconfirm: true,
      disabled: !enableBatchDeleteBtn,
      onConfirm: handleDelete,
    },
  ];

  const handleTableChange = async (pagination: any) => {
    const paramsTableChange = {
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      pageCount: pagination.total,
    };
    dispatch({
      type: 'dmMessage/getFetchPage',
      payload: { url: '/dm-process-service/config/vins', ...paramsTableChange }
      ,
      callback: (res: any) => {
        const list = res?.data?.list;
        if (list.length === 0 && pagination.current > 1) {
          handleFlash({
            pageNum: 1,
            pageSize: pagination.pageSize
          });
        } else {
          setVehichleList(list);
          setParams({
            pageNum: res.data.pageNum,
            pageSize: res.data.pageSize
          });
          setPageCount(res.data.pageCount);
        };
      }
    });
  };

  // 禁用过期时间
  const [curSettingHours, setCurSettingHours] = useState<number>();
  const [curSettingMinutes, setCurSettingMinutes] = useState<number>();
  const [curSettingDate, setCurSettingDate] = useState('');

  const disabledDate = (current: any) => {
    if ((curSettingHours && curSettingHours <= moment().hours()) || curSettingHours === 0) {
      if (curSettingMinutes && curSettingMinutes - 1 > moment().minutes()) {
        return current && current < moment().startOf('day');
      };
      return current && current < moment().endOf('day');
    };
    // Can not select days before today
    return current && current < moment().startOf('day');
  };
  const disabledDateTime = (date: any) => {
    // 获取的当前时间
    const now = moment();
    const currentDay = now.date();
    const currentHours = now.hours();
    const currentMinutes = now.minutes();
    const nowString = now.add(2, 'minutes').format('HH:mm:ss');
    const nowDateString = now.add(1, 'days').format('YYYY-MM-DD');
    // 设置的时间
    const settingHours = moment(date).hours();
    const settingDay = moment(date).date();
    setCurSettingHours(settingHours);
    setCurSettingMinutes(moment(date).minutes());
    setDefaultDate(nowString);
    setCurSettingDate(nowDateString);
    if (date && settingDay === currentDay && settingHours === currentHours) {
      // 设置的时间在现在这个小时，禁用该小时该分钟之前的时间
      return {
        disabledHours: () => range(0, currentHours),
        disabledMinutes: () => range(0, currentMinutes + 2)
      };
    } else if (date && settingDay === currentDay && settingHours > currentHours) {
      // 设置的时间在这小时后，只禁用该小时之前的时间
      return {
        disabledHours: () => range(0, currentHours),
      };
    } else if (date && settingDay === currentDay && settingHours < currentHours) {
      // 先设置了小时小于当前，再设置日期为当天，需要禁用当天现在这小时之前的时间和所有分
      return {
        disabledHours: () => range(0, currentHours),
        disabledMinutes: () => range(0, 59)
      };
    } else if (date && settingDay > currentDay) {
      // 设置的时间在当天之后的日期，不限制
      return {
        disabledHours: () => [],
        disabledMinutes: () => []
      }
    }
  };
  const range = (start: number, end: number) => {
    const result = [];
    for (let i = start; i < end; i++) {
      result.push(i);
    }
    return result;
  };

  return (
    <Card>
      <div style={{ display: 'flex', justifyContent: 'end', marginBottom: '8px' }}>
        <PateoAuthButtons btns={btns} max={4} pathname={pathname} />
      </div>
      <Modal
        visible={editModalVisible}
        title={`更新${editingData.vin}`}
        destroyOnClose={true}
        onOk={handleUpdate}
        onCancel={closeEditModal}
        width={800}
      >
        <Form
          {...layout}
          form={form}
          // preserve={false}
          style={{ maxWidth: 800, paddingBottom: 0 }}
          initialValues={editingData}
        >
          <Row align='top' gutter={[8, 8]}>
            <Col flex={'300px'}>
              <Form.Item
                label="Vin"
                name="vin"
                rules={[{ required: true, message: 'vin 不能为空！' }]}
              >
                <Input placeholder='vin' disabled />
              </Form.Item>
            </Col>
            <Col>
              <Form.Item
                label="过期时间"
                name="expireTime"
                rules={[{ required: true, message: '请选择过期时间！' },
                {
                  validator: (_, values) => {
                    if (values && values.isBefore(moment().add(2, 'minutes'))) {
                      return Promise.reject(new Error('时间不能早于当前时间!'));
                    };
                    return Promise.resolve();
                  }
                }
                ]}
              >
                <DatePicker placeholder="过期时间"
                  defaultValue={moment(curSettingDate, 'YYYY-MM-DD')}
                  showTime={{ defaultValue: moment(defaultDate, 'hh:mm:ss') }} showNow={false}
                  disabledDate={disabledDate} disabledTime={disabledDateTime} />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>

      <Modal
        visible={modalVisible}
        title="批量添加"
        maskClosable={false}
        destroyOnClose={true}
        onOk={handleCreate}
        onCancel={closeModal}
        width={800}
      >
        <Form
          {...layout}
          form={form}
          // preserve={false}
          style={{ maxWidth: 800, paddingBottom: 0 }}
          initialValues={{ formValues: [{ vin: '', expireTime: '' }] }}
        >
          <Form.List
            name="formValues"
            rules={[
              {
                validator: async (_, list) => {
                  console.log('list', list);
                  if (!list || list.length < 1) {
                    return Promise.reject(new Error('至少填写一条'));
                  }
                },
              },
            ]}
          >
            {(fields, { add, remove }, { errors }) => (
              <>
                {fields.map((field, index) => (
                  <Row key={field.key} align="top" gutter={[8, 8]}>
                    <Col flex={'300px'}>
                      <Form.Item
                        label="Vin"
                        name={[field.name, 'vin']}
                        rules={[
                          {
                            required: true,
                            whitespace: true,
                            message: 'Vin不能为空',
                          },
                        ]}
                      >
                        <Input placeholder="Vin" />
                      </Form.Item>
                    </Col>
                    <Col>
                      <Form.Item
                        label="过期时间"
                        name={[field.name, 'expireTime']}
                        rules={[
                          { type: 'object' as const, required: true, message: '请选择过期时间！' },
                          {
                            validator: (_, values) => {
                              if (values && values.isBefore(moment().add(1, 'minutes'))) {
                                return Promise.reject(new Error('时间不能早于当前时间!'));
                              };
                              return Promise.resolve();
                            }
                          }
                        ]}
                      >
                        <DatePicker placeholder="过期时间"
                          initialValue={moment(curSettingDate, 'YYYY-MM-DD')}
                          showTime={{ defaultValue: moment(defaultDate, 'hh:mm:ss') }}
                          showNow={false}
                          disabledDate={disabledDate} disabledTime={disabledDateTime}
                        />
                      </Form.Item>
                    </Col>
                    <Col style={{ paddingTop: '6px' }}>
                      {fields.length > 1 ? (
                        <MinusCircleOutlined
                          style={{ marginRight: '8px' }}
                          onClick={() => {
                            remove(field.name);
                          }}
                        />
                      ) : null}
                      {fields.length - 1 === index ? (
                        <PlusCircleOutlined
                          onClick={() => {
                            add(field.name);
                          }}
                        />
                      ) : null}
                    </Col>
                  </Row>
                ))}
                {errors.length ? (
                  <Form.Item>
                    <Form.ErrorList errors={errors} />
                  </Form.Item>
                ) : null}
              </>
            )}
          </Form.List>
        </Form>
      </Modal>
      <Table
        {...tableProps}
        onChange={handleTableChange}
      />
    </Card >
  );
};

export default connect(({ abilityModel, loading }: { abilityModel: any; loading: any }) => ({
  abilityModel,
  loading: loading.models.abilityModel,
}))(DMMessageManagement);
